package com.mikhailenko.transportMVC.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.CriteriaNotFoundExeption;
import com.mikhailenko.transportMVC.model.Criteria;
import com.mikhailenko.transportMVC.repository.CriteriaRepository;
import com.mikhailenko.transportMVC.service.CriteriaService;

@Service
public class CriteriaServiceImpl implements CriteriaService {

	@Autowired
	private CriteriaRepository criteriaRepository;
	
	@Override
	@Transactional
	public Criteria create(Criteria criteria) {
		Criteria createdCriteria = criteria;
		return criteriaRepository.saveAndFlush(createdCriteria);
	}

	@Override
	@Transactional(rollbackFor=CriteriaNotFoundExeption.class)
	public Criteria delete(int id) throws CriteriaNotFoundExeption {
		Criteria deletedCriteria = criteriaRepository.findOne(id);
		
		if (deletedCriteria == null){
			throw new CriteriaNotFoundExeption();
		}
		
		criteriaRepository.delete(id);
		return deletedCriteria;
	}

	@Override
	@Transactional
	public List<Criteria> findAll() {
		return criteriaRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=CriteriaNotFoundExeption.class)
	public Criteria update(Criteria criteria) throws CriteriaNotFoundExeption {
		Criteria updatedCriteria = criteriaRepository.findOne(criteria.getId());
		
		if (updatedCriteria == null){
			throw new CriteriaNotFoundExeption();
		}
		
		updatedCriteria.setFirm(criteria.getFirm());
		updatedCriteria.setName(criteria.getName());
		updatedCriteria.setTerm(criteria.getTerm());
		updatedCriteria.setGroup(criteria.getGroup());
		updatedCriteria.setStatus(criteria.getStatus());
		return updatedCriteria;
	}

	@Override
	@Transactional
	public Criteria findById(int id) {
		return criteriaRepository.findOne(id);
	}

    @Override
    public List<Criteria> findByGroup(int id) {
        return criteriaRepository.findByGroup(id);
    }

}
